<template>
	<u-upload v-if="slotFlag" :accept="accept" :file-list="fileList" @after-read="afterRead" @delete="deletePic" max-count="1"
			  :width="width" :height="height" :upload-text="_uploadText" :disabled="disabled">
			<slot></slot>
	</u-upload>
	<u-upload v-else :accept="accept" :file-list="fileList" @after-read="afterRead" @delete="deletePic" max-count="1"
			  :width="width" :height="height" :upload-text="_uploadText" :disabled="disabled">
	</u-upload>
</template>

<script setup>

const props = defineProps({
	modelValue: {
		type: Object,
		default: null,
	},
	accept: {
		type: String,
		default: 'image'
	},
	width: {
		type: String,
		default: '192rpx'
	},
	height: {
		type: String,
		default: '192rpx'
	},
	uploadText: {
		type: String,
		default: null
	},
	disabled: {
		type: Boolean,
		default: false
	},
	slotFlag: {
		type: Boolean,
		default: false
	}
})

const emits = defineEmits(['update:modelValue'])
const value = computed({
	get() {
		return props.modelValue
	},
	set(val) {
		emits('update:modelValue', val)
	}
})

const _uploadText = computed(() => {
	if (props.uploadText) {
		return props.uploadText
	} else if (props.accept === 'image') {
		return '选择图片'
	} else if (props.accept === 'video') {
		return '选择视频'
	} else {
		return '选择文件'
	}
})

const fileList = computed(() => {
	if(props.modelValue){
		if (props.modelValue.data) {
			return [props.modelValue.data]
		}else if(props.modelValue.path){
			return [{
				url: props.modelValue.path,
				thumb: props.modelValue.path,
				status: 'success',
				type: "image"
			}]
		}
		return []
	}
	return []
})
// 删除图片
const deletePic = () => value.value = null

// 新增图片
const afterRead = async (event) => {
	value.value = {
		data: {
			...event.file,
			status: 'uploading',
			message: '上传中'
		}
	}
	qly.oss.upload(event.file).then((result) => {
		let tempItem = value.value
		value.value = {
			...result,
			data: {
				...tempItem.data,
				status: 'success',
				message: '',
			}
		}
	}).catch(() => {
		value.value = null
	})

};

</script>

<style scoped>

</style>
